package com.cn.ZhiKeDianShang.util.TimeSelect;

import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.app.Dialog;
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.model.response.RroandCityBean;
import com.cn.ZhiKeDianShang.util.JsonUitl;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.JsonCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 创建人：lwd
 * 时  间：2018/4/24 10:12
 */
public class CustomAdressPicker {

    //选择的省的名字
    String proName;
    //选择的省的id
    String proId;
    //选择的城市名字
    String cityName;
    //选择的城市的id
    String cityId;

    /**
     * 定义结果回调接口
     */
    public interface ResultHandler {
        void handle(String proName, String proId, String cityName, String cityId);
    }

    public enum SCROLL_TYPE {
        HOUR(1),
        MINUTE(2);

        SCROLL_TYPE(int value) {
            this.value = value;
        }

        public int value;
    }

    private int scrollUnits = SCROLL_TYPE.HOUR.value + SCROLL_TYPE.MINUTE.value;
    private ResultHandler handler;
    private Context context;
    private boolean canAccess = false;

    private Dialog datePickerDialog;
    private AdressPickerView year_pv, month_pv;

    private static final int MAX_MINUTE = 59;
    private static final int MAX_HOUR = 23;
    private static final int MIN_MINUTE = 0;
    private static final int MIN_HOUR = 0;
    private static final int MAX_MONTH = 12;

    private List<RroandCityBean.DataBean> year, month;
    private TextView tv_cancle, tv_select;
    List<RroandCityBean.DataBean> mdata;

    public CustomAdressPicker(Context context, List<RroandCityBean.DataBean> data, ResultHandler resultHandler) {
        canAccess = true;
        this.context = context;
        this.handler = resultHandler;
        this.mdata = data;
        initDialog();
        initView();
    }

    private void initDialog() {
        if (datePickerDialog == null) {
            datePickerDialog = new Dialog(context, R.style.time_dialog);
            datePickerDialog.setCancelable(false);
            datePickerDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            datePickerDialog.setContentView(R.layout.custom_adress_picker);
            Window window = datePickerDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            datePickerDialog.setCanceledOnTouchOutside(true);
            WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(dm);
//            window.setWindowAnimations(R.style.dialogstyle); // 添加动画
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.width = dm.widthPixels;
            window.setAttributes(lp);
        }
    }

    private void initView() {
        year_pv = (AdressPickerView) datePickerDialog.findViewById(R.id.year_pv);
        month_pv = (AdressPickerView) datePickerDialog.findViewById(R.id.month_pv);
        tv_cancle = (TextView) datePickerDialog.findViewById(R.id.tv_cancle);
        tv_select = (TextView) datePickerDialog.findViewById(R.id.tv_select);

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                datePickerDialog.dismiss();
            }
        });

        tv_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handler.handle(proName, proId, cityName, cityId);
                datePickerDialog.dismiss();
            }
        });
    }


    private void initTimer() {
        if (year == null) year = new ArrayList<>();
        if (month == null) month = new ArrayList<>();
        year.clear();
        month.clear();

        year = mdata;
        // 现在是默认显示第一个省份，获得第一个省份的市信息
        getCity(mdata.get(0).getId(), false);
    }


    /**
     * 获取选中省 里面的城市   selectSomePro  true滑动到某个省时候请求数据 ,false为一开始初始化请求
     */
    private void getCity(int pid, Boolean selectSomePro) {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        params.put("pid", pid + "");
        HttpUtils.post().url(AppConfig.COMMON_CITY)
                .params(params)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onResponse(String result) {
                        RroandCityBean bean = (RroandCityBean) JsonUitl.stringToObject(result, RroandCityBean.class);
                        if (selectSomePro) {
                            month = bean.getData();
                            month_pv.setData(month);
                            //这里设置选中第一个数据
                            if (month.size() > 0) {
                                month_pv.setSelected(0);
                                cityName = month.get(0).getName();
                                cityId = month.get(0).getId() + "";
                            } else {
                                cityName = "";
                                cityId = "";
                            }

                        } else {
                            month = bean.getData();
                            loadComponent();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    private void loadComponent() {
        year_pv.setData(year);
        if (year.size() > 0) {
            //        //省默认显示 第一个
            year_pv.setSelected(0);
            //取到省 的名字和id
            proName = year.get(0).getName();
            proId = year.get(0).getId() + "";
        }

        month_pv.setData(month);
        if (month.size() > 0) {
            //是显示中间的一个   不设置位置默认显示中间的
            int monthSelected = month.size() / 4;
            cityName = month.get(monthSelected).getName();
            cityId = month.get(monthSelected).getId() + "";
        } else {
            cityName = "";
            cityId = "";
        }
        executeScroll();
    }

    private void addListener() {
        year_pv.setOnSelectListener(new AdressPickerView.onSelectListener() {
            @Override
            public void onSelect(RroandCityBean.DataBean bean) {
                //截取年
                Log.d("Debug", "市选中了" + bean.getName() + "pid" + bean.getId());
                //取到省 的名字和id
                proName = bean.getName();
                proId = bean.getId() + "";
                getCity(bean.getId(), true);
            }
        });

        month_pv.setOnSelectListener(new AdressPickerView.onSelectListener() {
            @Override
            public void onSelect(RroandCityBean.DataBean bean) {
                cityName = bean.getName();
                cityId = bean.getId() + "";
                Log.d("Debug", "city选中了" + bean.getName() + "pid" + bean.getId());
            }
        });

    }


    private void executeAnimator(View view) {
        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f, 0f, 1f);
        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX", 1f, 1.3f, 1f);
        PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY", 1f, 1.3f, 1f);
        ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY, pvhZ).setDuration(200).start();
    }

    private void executeScroll() {
        year_pv.setCanScroll(year.size() > 1);
        month_pv.setCanScroll(month.size() > 1);
    }

    private int disScrollUnit(SCROLL_TYPE... scroll_types) {
        if (scroll_types == null || scroll_types.length == 0) {
            scrollUnits = SCROLL_TYPE.HOUR.value + SCROLL_TYPE.MINUTE.value;
        } else {
            for (SCROLL_TYPE scroll_type : scroll_types) {
                scrollUnits ^= scroll_type.value;
            }
        }
        return scrollUnits;
    }

    public void show() {
        if (canAccess) {
            canAccess = true;
            initTimer();
            //滑动监听
            addListener();
            datePickerDialog.show();
        }
    }


    /**
     * 设置日期控件是否可以循环滚动
     */
    public void setIsLoop() {
        if (canAccess) {
            this.year_pv.setIsLoop(false);
            this.month_pv.setIsLoop(false);
        }
    }


}